import pygame
import random

pygame.init()

WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# 游戏设置
player_width = 50
player_height = 50
player_x = 100
player_y = HEIGHT - player_height - 10
player_vel = 5
gravity = 1

obstacles = []
jump_count = 10
is_jumping = False


class Obstacle:
    def __init__(self):
        self.x = WIDTH
        self.y = HEIGHT - 50
        self.width = 50
        self.height = 50
        self.color = (255, 0, 0)
        self.vel = 5

    def move(self):
        self.x -= self.vel

    def draw(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))


def main():
    global player_y, is_jumping, jump_count
    running = True
    while running:
        screen.fill((0, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE] and not is_jumping:
            is_jumping = True

        if is_jumping:
            if jump_count >= -10:
                neg = 1
                if jump_count < 0:
                    neg = -1
                player_y -= (jump_count ** 2) * 0.5 * neg
                jump_count -= 1
            else:
                is_jumping = False
                jump_count = 10

        # 随机生成障碍物
        if random.randint(1, 100) == 1:
            obstacles.append(Obstacle())

        # 移动和绘制障碍物
        for obstacle in obstacles:
            obstacle.move()
            obstacle.draw()
            if obstacle.x < 0:
                obstacles.remove(obstacle)

        # 绘制玩家
        pygame.draw.rect(screen, (0, 128, 255), (player_x, player_y, player_width, player_height))

        pygame.display.update()
        clock.tick(30)


if __name__ == '__main__':
    main()
